import { DataListPage } from "maishu-chitu-admin/static";
import { ReceivementAccount } from "account/entities";
import { dataSources, User } from "../services/data-sources";
import { boundField, dateTimeField, GridViewCell, customField, } from "maishu-wuzhui-helper";
import ReactDOM = require("react-dom");
import React = require("react");
import * as ui from "maishu-ui-toolkit";
import { PageProps } from "maishu-chitu-react";
import { AccountService } from "services/account-service";
import { FormValidator, rules } from "maishu-dilu";

interface State {
    accounts: ReceivementAccount[]
}



export default class UserListPage extends DataListPage<User, PageProps, State> {

    private account = this.props.createService(AccountService);

    constructor(props) {
        super(props);

        this.state = { accounts: [] };
    }

    dataSource = dataSources.user;
    itemName = "用户";
    columns = [
        boundField<User>({ dataField: "Mobile", headerText: "手机" }),
        boundField<User>({ dataField: "NickName", headerText: "昵称" }),
        boundField<User>({ dataField: "Gender", headerText: "性别" }),
        boundField<User>({ dataField: "Balance", headerText: "余额", dataFormatString: "￥{C2}", itemStyle: { textAlign: "right" } }),
        dateTimeField<User>({ dataField: "CreateDateTime", headerText: "注册日期" }),
    ];

    operationColumn = customField<User>({
        headerText: "操作",
        headerStyle: { textAlign: "center", width: "200px" },
        itemStyle: { textAlign: "center" },
        createItemCell: (dataItem) => {
            let cell = new GridViewCell();
            ReactDOM.render(<>
                <button key="records" className="btn btn-success btn-minier">
                    <i className="icon-reorder" />
                    <span>充值记录</span>
                </button>
                <button key="recharge" className="btn btn-info btn-minier"
                    onClick={() => this.showRechargeDialog(dataItem)}>
                    <i className="icon-money" />
                    <span>充值</span>
                </button>
            </>, cell.element);
            return cell;
        }
    })

    private selectedUserInfo: User;
    private accountInput: HTMLInputElement;
    private mobileElement: HTMLElement;
    private rechargeDialogElement: HTMLElement;
    private amountInput: HTMLInputElement;
    private receivementAccountElement: HTMLSelectElement;
    private validator: FormValidator;

    showRechargeDialog(userInfo: User) {
        // account: string, mobile: string
        this.selectedUserInfo = userInfo;
        let account = userInfo.Id;
        let mobile = userInfo.Mobile;

        console.assert(account != null);
        console.assert(mobile != null)

        this.accountInput.value = account;
        this.mobileElement.innerHTML = mobile;

        ui.showDialog(this.rechargeDialogElement);
    }

    async recharge() {
        let isValid = await this.validator.check();
        if (!isValid)
            return;

        let userId = this.accountInput.value;
        let amount = Number.parseFloat(this.amountInput.value);

        let message = `账户：${this.mobileElement.innerHTML}<br/><br/>金额：${this.amountInput.value}`;
        let bill = await this.account.createBill(userId, amount);
        ui.confirm({
            title: "请确认", message,
            confirm: async () => {
                let r = await this.account.recharge(userId, bill.Id, this.receivementAccountElement.value);
                console.assert(this.selectedUserInfo != null);
                this.selectedUserInfo.Balance = r.Balance;
                this.dataSource.updated.fire(this.dataSource, this.selectedUserInfo);

                ui.hideDialog(this.rechargeDialogElement);
                ui.alert('冲值成功');
            }
        })
    }

    componentDidMount() {
        console.assert(super.componentDidMount != null);
        super.componentDidMount();

        let { required, greaterThan } = rules;
        this.validator = new FormValidator(this.rechargeDialogElement,
            { name: "amount", rules: [greaterThan(() => 0, "金额必须大于 0")] },
            { name: 'receivementAccount', rules: [required('请选择收款账户')] }
        )

        this.account.receivementAccountList().then(items => {
            this.setState({ accounts: items });
        })

    }

    render() {
        let { accounts } = this.state;
        accounts = accounts || [];

        return <>
            {super.render()}

            <div key={30} className="modal fade" ref={(e: HTMLElement) => this.rechargeDialogElement = e || this.rechargeDialogElement}>
                <div className="modal-dialog">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal">
                                <span aria-hidden="true">&times;</span><span className="sr-only">Close</span>
                            </button>
                            <h4 className="modal-title">充值</h4>
                        </div>
                        <div className="modal-body form-horizontal">
                            <div className="form-group">
                                <label className="col-sm-2 control-label">充值账户</label>
                                <div className="col-sm-10">
                                    <div ref={(m: HTMLElement) => this.mobileElement = m || this.mobileElement}></div>
                                    <input name="userId" className="form-control" placeholder="请输入要充值的账户"
                                        readOnly={true} type="hidden"
                                        ref={(e: HTMLInputElement) => this.accountInput = e || this.accountInput} />
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-sm-2 control-label">金额</label>
                                <div className="col-sm-10">
                                    <input name="amount" className="form-control" placeholder="请输入要充值的金额"
                                        ref={(e: HTMLInputElement) => this.amountInput = e || this.amountInput} />
                                </div>
                            </div>
                            <div className="form-group">
                                <label className="col-sm-2 control-label">收款账户</label>
                                <div className="col-sm-10">
                                    <select name="receivementAccount" className="form-control"
                                        ref={(e: HTMLSelectElement) => this.receivementAccountElement = e || this.receivementAccountElement}>
                                        <option value="">请选择收款账户</option>
                                        {accounts.map(o =>
                                            <option key={o.Id} value={o.Id}>{o.Name}</option>
                                        )}
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button className="btn btn-default"
                                onClick={() => ui.hideDialog(this.rechargeDialogElement)}>取消</button>
                            <button className="btn btn-primary"
                                ref={(e: HTMLButtonElement) => {
                                    if (!e) return;

                                    e.onclick = ui.buttonOnClick(() => this.recharge());
                                }}>确定</button>
                        </div>
                    </div>
                </div>
            </div>
        </>
    }
}

